<script lang="ts" setup>
import type { DropMenu } from '#/components/dropdown';

import { onMounted, ref } from 'vue';

import { $t } from '@vben/locales';

import { useFs } from '@fast-crud/fast-crud';
import { Button } from 'ant-design-vue';

import { getValidateRulesByFs } from '#/api/common/validateByFs';
import {
  DefGenTableApi,
  DefGenTableConfig,
} from '#/api/devOperation/developer/defGenTable';
import { Dropdown } from '#/components/dropdown';
import { ActionEnum } from '#/enums/commonEnum';
import { TemplateEnum } from '#/enums/system';
import { useMessage } from '#/hooks/web/useMessage';
import { blobToObj, downloadByResponse } from '#/utils/file/download';

import { createCrudOptions, frontRules } from './data/crud';
import ImportModal from './modules/ImportModal.vue';
import PreviewModal from './modules/PreviewModal.vue';

defineOptions({
  name: '代码生成',
  inheritAttrs: false,
});

const importRef = ref();
const previewRef = ref();
const { createMessage } = useMessage();
const { crudRef, crudBinding, crudExpose, appendCrudOptions, context } = useFs({
  createCrudOptions,
  context: { importRef, previewRef },
});

// 页面打开后获取列表数据
onMounted(async () => {
  const addFormOptions = await getValidateRulesByFs({
    Api: DefGenTableConfig.Save,
    mode: ActionEnum.ADD,
    customRules: frontRules.addForm.rules,
    trigger: 'change',
  });
  const editFormOptions = await getValidateRulesByFs({
    Api: DefGenTableConfig.Update,
    mode: ActionEnum.EDIT,
    customRules: frontRules.editForm.rules,
    trigger: 'change',
  });
  appendCrudOptions({ ...addFormOptions, ...editFormOptions });
  crudExpose.doRefresh();
});

function handleSuccess() {
  crudExpose.doRefresh();
}
const downloadOptions: DropMenu[] = [
  { text: '下载后端', event: TemplateEnum.BACKEND },
  { text: '下载前端（Vben）', event: TemplateEnum.WEB_PLUS },
  { text: '下载前端（Soybean）', event: TemplateEnum.WEB_SOYBEAN },
  { text: '下载前端（vben5）', event: TemplateEnum.WEB_VBEN5 },
];
const generatorOptions: DropMenu[] = [
  { text: '生成后端', event: TemplateEnum.BACKEND },
  { text: '生成前端（Vben）', event: TemplateEnum.WEB_PLUS },
  { text: '生成前端（Soybean）', event: TemplateEnum.WEB_SOYBEAN },
  { text: '下载前端（vben5）', event: TemplateEnum.WEB_VBEN5 },
];

async function handleGenerator(template: string) {
  const ids = (context as any).selectedIds;
  if (ids?.length > 0) {
    const defGenVo = { ids, template };
    await DefGenTableApi.generatorCode(defGenVo);
  } else {
    createMessage.warning('请至少选择一条数据');
  }
}
async function handleDownload(template: string) {
  const ids = (context as any).selectedIds;
  if (ids?.length > 0) {
    try {
      const response = await DefGenTableApi.downloadZip(ids, template);
      if (response) {
        downloadByResponse(response);
        createMessage.success($t('common.tips.downloadSuccess'));
      } else {
        createMessage.error(
          '下载失败，请认真检查【生成信息】是否填写完整并保存成功！',
        );
      }
    } catch (error: any) {
      if (error?.response?.data) {
        const obj = (await blobToObj(error?.response?.data)) as any;
        createMessage.error(obj.msg);
      } else {
        const obj = (await blobToObj(error)) as any;
        createMessage.error(obj.msg);
      }
    }
  } else {
    createMessage.warning('请至少选择一条数据');
  }
}
</script>

<template>
  <FsPage>
    <FsCrud ref="crudRef" v-bind="crudBinding">
      <template #actionbar-right>
        <Dropdown
          :trigger="['hover']"
          :drop-menu-list="downloadOptions"
          @select="handleDownload"
        >
          <Button>下载</Button>
        </Dropdown>
        <Dropdown
          :trigger="['hover']"
          :drop-menu-list="generatorOptions"
          @select="handleGenerator"
        >
          <Button>生成</Button>
        </Dropdown>
      </template>
    </FsCrud>
    <PreviewModal ref="previewRef" @success="handleSuccess" />
    <ImportModal ref="importRef" @success="handleSuccess" />
  </FsPage>
</template>
